//
//  SendMsgVC.m
//  BrushFace
//
//  Created by timer_q on 16/1/25.
//  Copyright © 2016年 Zzz. All rights reserved.
//

#import "SendMsgVC.h"
#import "ARRequestModel.h"
#import "NavHelper.h"
#import "DeviceInfo.h"

@interface SendMsgVC ()<UITableViewDataSource,UITableViewDelegate,AROtherBottomVDelegate>
{
    UITableView *_tableView;
    NSString *_userid;
}
@end

@implementation SendMsgVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navBar setTitle:@"弹幕"];
    [self.navBar setLeftBtn:NAV_BAR_LEFT_BTN_TYPE_BLUE];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault]; 
    self.view.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    [self otherBottomCreate];
    _resultArray = [[NSMutableArray alloc] init];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-45-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [ARRequestModel sharedInstance].hopeId = self.hopeid;
    [self sendMsgSuccess];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//泡泡文本
- (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf withPosition:(int)position{
    
    //计算大小
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    
    // build single chat bubble cell with given text
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    //背影图片
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width/2) topCapHeight:floorf(bubble.size.height/2)]];
    NSLog(@"%f,%f",size.width,size.height);
    
    
    //添加文本信息
    UILabel *bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?15.0f:22.0f, 20.0f, size.width+10, size.height+10)];
    bubbleText.backgroundColor = [UIColor clearColor];
    bubbleText.font = font;
    bubbleText.numberOfLines = 0;
    bubbleText.lineBreakMode = NSLineBreakByWordWrapping;
    bubbleText.text = text;
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+20.0f);
    
    if(fromSelf)
        returnView.frame = CGRectMake(SCREEN_WIDTH-position-(bubbleText.frame.size.width+30.0f), 20.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    else
        returnView.frame = CGRectMake(position, 20.0f, bubbleText.frame.size.width+30.0f, bubbleText.frame.size.height+30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    return returnView;
}


#pragma UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _resultArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = [_resultArray objectAtIndex:indexPath.row];
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize size = [[dict objectForKey:@"content"] sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    
    return size.height+44+20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }else{
        for (UIView *cellView in cell.subviews){
            [cellView removeFromSuperview];
        }
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor clearColor];
    NSDictionary *dict = [_resultArray objectAtIndex:indexPath.row];
    
    
    //创建头像
    UIImageView *photo ;
    UILabel   *nicklabel;
    if ([_userid isEqualToString:dict[@"friendid"]]) {
        if (photo) {
            [photo removeFromSuperview];
        }
        photo = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-60, 10, 50, 50)];
        photo.tag = indexPath.row;
        photo.layer.cornerRadius = 25;
        photo.clipsToBounds = YES;
        [cell addSubview:photo];
        
        [photo addTapAction:^(UIImageView *sender) {
           [NavHelper gotoContactDetailVCWithUserId:[[_resultArray objectAtIndex:sender.tag] objectForKey:@"friendid"]];
        }];
        
        [photo sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERIMAGE_FETCH,dict[@"friendid"]]] placeholderImage:[UIImage imageNamed:@"photo1"]];
        nicklabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-270, 10, 200, 20)];
        nicklabel.text = [NSString stringWithFormat:@"%@  %@",dict[@"friendname"],[self forTheRestOfTimeStr:dict[@"editetime"]]];
        nicklabel.font = [UIFont systemFontOfSize:12];
        nicklabel.textAlignment = NSTextAlignmentRight;
        nicklabel.textColor = [UIColor lightGrayColor];
        [cell addSubview:nicklabel];
        [cell addSubview:[self bubbleView:[dict objectForKey:@"content"] from:YES withPosition:65]];
    }else{
        if (photo) {
            [photo removeFromSuperview];
        }
        photo = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
        photo.tag = indexPath.row;
        [cell addSubview:photo];
        photo.layer.cornerRadius = 25;
        photo.clipsToBounds = YES;
        [photo addTapAction:^(UIImageView *sender) {
            [NavHelper gotoContactDetailVCWithUserId:[[_resultArray objectAtIndex:sender.tag] objectForKey:@"friendid"]];
        }];
        nicklabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 10, 200, 20)];
        nicklabel.text = [NSString stringWithFormat:@"%@%@",dict[@"friendname"],[self forTheRestOfTimeStr:dict[@"editetime"]]];
        nicklabel.font = [UIFont systemFontOfSize:12];
        nicklabel.textColor = [UIColor lightGrayColor];
        [cell addSubview:nicklabel];
        [photo sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERIMAGE_FETCH,dict[@"friendid"]]] placeholderImage:[UIImage imageNamed:@"photo"]];
        [cell addSubview:[self bubbleView:[dict objectForKey:@"content"] from:NO withPosition:65]];
    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)otherBottomCreate{
    self.otherBottomView = [AROtherBottomV loadBundleNib];
    self.otherBottomView.frame = CGRectMake(0, SCREEN_HEIGHT-45, SCREEN_WIDTH, 44);
    self.otherBottomView.delegate = self;
    self.otherBottomView.hopeID = self.hopeid;
    [self.view addSubview:self.otherBottomView];
}
- (void)sendMsgSuccess{
    [[ARRequestModel sharedInstance] fetchPingLunListAndCB:^(id output) {
        _userid = output[@"userid"];
        [_resultArray removeAllObjects];
        [_resultArray addObjectsFromArray:[output objectForKey:@"data"]];
        [_tableView reloadData];
    }];
}
- (NSString *)timerStrWithTime:(NSString *)time{
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:[time doubleValue]/1000+28800];
    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"MM-dd HH:MM"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}
- (NSString *)forTheRestOfTimeStr:(NSString *)timeStr{
    NSString *nowStr = [DeviceInfo getCurDeviceTimeStr];
    NSInteger nowTime = [nowStr integerValue];
    NSInteger sendTime = [timeStr integerValue];
    NSInteger temp = nowTime/1000 - sendTime/1000;
    if (temp<60) {
        return [NSString stringWithFormat:@"%ld秒前",temp];
    }
    if (temp<3600) {
        return [NSString stringWithFormat:@"%ld分钟前",temp/60];
    }
    if (temp<86400) {
        return [NSString stringWithFormat:@"%ld小时前",temp/3600];
    }
    if (temp<172800) {
        return @"一天前";
    }
    return [self timerStrWithTime:timeStr];
}
@end
